package com.future.config;

import java.util.concurrent.*;


import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ThreadPoolConfig {
    /**
     * 群聊消息专用线程池
     */
    @Bean("chatMessagePool")
    public ExecutorService chatMessgePool(){
        //核心线程数
        int corePoolThread= Runtime.getRuntime().availableProcessors()*2;
        //最大线程数
        int maximumPoolSize=50;
        //空闲线程最大存活时间
        Long keepAliveTime=60L;
        //任务队列：缓冲待执行的发送任务
        BlockingQueue<Runnable> workQueue=new LinkedBlockingDeque<>(1000);
        //拒绝策略
        RejectedExecutionHandler handler =new ThreadPoolExecutor.CallerRunsPolicy();
        //线程命名规则
        ThreadFactory factory=new ThreadFactory(){
            private int count=0;
            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread=new Thread(r);
                thread.setName("chat-sender-"+count++);
                return thread;
            }
        };
        return new ThreadPoolExecutor(
                corePoolThread,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                factory,
                handler
        );
    }
    /**
     * 离线消息推送专用线程池
     */
    @Bean("offlineMessageExecutor")
    public ExecutorService offlineMessageExecutor() {
        // 核心线程数：根据CPU核心数和业务量调整（IO密集型任务可设大些）
        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
        // 最大线程数：控制峰值并发
        int maximumPoolSize = Runtime.getRuntime().availableProcessors() * 4;
        // 空闲线程存活时间：60秒
        long keepAliveTime = 60L;
        // 任务队列：缓冲待处理的推送任务（容量根据消息峰值调整）
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1000);
        // 线程工厂：自定义线程名，便于排查问题
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 0;
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("offline-push-thread-" + count++);
                return thread;
            }
        };
        // 拒绝策略：任务满时让提交线程执行（减缓提交速度，避免消息丢失）
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                threadFactory,
                handler
        );
    }
}
